#! /bin/bash
# USB设备绑定脚本，使用lsusb命令查询设备号，在主函数中设置绑定的值
# 可以集成到ros中去  <node name="setup_udev" pkg="XXX" type="setup_udev.sh" output="screen" launch-prefix="bash "/>

# 请填写密码
SUDO_PASSWORD="322123"

sudo_with_password() {
    echo "$SUDO_PASSWORD" | sudo -S "$@" 2>/dev/null
}

detect_device() {
    local vendor_id="$1"
    local product_id="$2"
    local current_device=""
    
    local usb_info=$(lsusb | grep "${vendor_id}:${product_id}")
    if [ ! -z "$usb_info" ]; then
        # 脚本扫描/dev目录下的设备，查找匹配的设备，如果想加速的话，请修改“/dev/*”为“/dev/tty*”或其他
        for device in /dev/*; do
            if [ -e "$device" ]; then
                if [[ "$device" == /dev/media* ]]; then
                    continue
                fi
                local dev_path=$(udevadm info -q path -n "$device" 2>/dev/null)
                if [ ! -z "$dev_path" ]; then
                    local vendor=$(udevadm info -a -p "$dev_path" 2>/dev/null | grep -m1 "idVendor" | cut -d'"' -f2)
                    local product=$(udevadm info -a -p "$dev_path" 2>/dev/null | grep -m1 "idProduct" | cut -d'"' -f2)
                    if [ "$vendor" = "$vendor_id" ] && [ "$product" = "$product_id" ]; then
                        current_device="$device"
                        break
                    fi
                fi
            fi
        done
    fi
    
    if [ ! -z "$current_device" ]; then
        echo "$current_device"
        return 0
    else
        return 1
    fi
}

setup_device() {
    local symlink_name="$1"
    local vendor_id="$2"
    local product_id="$3"
    
    [ -L "$symlink_name" ] && sudo_with_password rm -f "$symlink_name"
    
    local detected_camera=$(detect_device "$vendor_id" "$product_id")
    if [ $? -eq 0 ]; then
        sudo_with_password ln -s "$detected_camera" "$symlink_name"
        sudo_with_password chmod 666 "$detected_camera"
        [ -L "$symlink_name" ] && sudo_with_password chmod 666 "$symlink_name"
        groups $USER | grep -q video || sudo_with_password usermod -a -G video $USER
        return 0
    else
        return 1
    fi
}

# 主设置函数, 前者为vendor_id，后者为product_id
setup_all_devices() {
    # 05c8:0441
    setup_device "/dev/video_8030p" "05c8" "0441"
    # 10bb:2b08
    setup_device "/dev/video_8060p" "10bb" "2b08"
}

setup_all_devices
